package com.sinodata.bsm.cicp.finder.linux;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.util.CommandReader;

/**
 * 
 * <p>
 * Description: 
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-12-26 AM 10:20:33   liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class LinuxMem extends LinuxFinder {

    private static final Logger logger = Logger.getLogger(LinuxMem.class);
    private static final int K = 1024;
    private static String CMDSTR = "free |grep ^Mem;getconf PAGESIZE";

    @SuppressWarnings("unchecked")
    @Override
    public List<String[]> find(String ip, Map params) {
        String[] memoryInfo = null;
        List<String[]> list = new ArrayList<String[]>();
        String strLine = null;
        BufferedReader reader = null;
        try {
            reader = CommandReader.getReader(ip, CMDSTR, 0, 0);
            while ((strLine = reader.readLine()) != null) {
                if (strLine.startsWith("Mem")) {
                    /*
                     * 每一个String[]表示一个资源数据，String[]数据定义如下：
                     * 第一个元素：资源的内部标示
                     * 第二个元素：资源名称
                     * 第三个元素：资源描述
                     * 第四-第N个参数：返回的属性值
                     */
                    memoryInfo = new String[5];
                    list.add(memoryInfo);
                    memoryInfo[0] = "0";
                    memoryInfo[1] = "Memory";
                    memoryInfo[2] = "Memory";
                    String[] ss = strLine.split("\\s+");
                    if (ss.length >= 2) {
                        memoryInfo[4] = Integer.parseInt(ss[1]) / K + "";
                    }
                } else {
                    if (memoryInfo != null) {
                        memoryInfo[3] = strLine.trim();
                    }
                }
            }
        } catch (Exception e) {
            logger.error("failed to find Linux memory", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("failed to close reader", e);
                }
            }
        }
        return list;
    }

}
